<template>
  <el-dialog width="50%" :title="!dataForm.id ? '用户新增' : '用户编辑'" :visible="myVisible" :before-close="handleCancel" :close-on-click-modal=false>
    <el-form :rules="rules" ref="dataForm" :model="dataForm" label-position="right" label-width="100px">
      <el-row>
        <el-col :span="16">
          <el-tabs type="border-card">
            <el-tab-pane label="用户基本信息">
              <el-form-item label="用户名" prop="userName">
                <el-input placeholder="请填写用户名" v-bind:disabled="disabledInput" v-model.trim="dataForm.userName"></el-input>
              </el-form-item>
              <!-- <el-form-item label="密码" prop="password" v-if="!dataForm.id">
                <el-input type="password" placeholder="请填写密码" v-model.trim="dataForm.password"></el-input>
              </el-form-item>
              <el-form-item label="密码" v-else>
                <el-input type="password" placeholder="请输入修改后的密码" v-model.trim="dataForm.password"></el-input>
              </el-form-item> -->
              <!-- <el-form-item label="姓名" prop="realName">
                <el-input placeholder="请填写姓名" v-model.trim="dataForm.realName"></el-input>
              </el-form-item> -->
              <el-form-item label="性别">
                <el-radio-group v-model="dataForm.sex">
                  <el-radio class="radio" :label="'1'">男</el-radio>
                  <el-radio class="radio" :label="'2'">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="账户状态">
                <el-radio-group v-model="dataForm.status">
                  <el-radio class="radio" :label="1">正常</el-radio>
                  <el-radio class="radio" :label="2">锁定</el-radio>
                  <el-radio class="radio" :label="3">删除</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="手机号码" prop="phone">
                <el-input placeholder="请填写手机号码" v-model="dataForm.phone" maxlength="11" show-word-limit></el-input>
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </el-col>
        <el-col :span="8">
          <el-tabs type="border-card">
            <el-tab-pane label="上传头像">
              <el-form ref="dataForm" :model="dataForm" style="height:250px">
                <el-upload class="avatar-uploader" action="" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                  <img v-if="imageUrl" :src="imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-card class="box-card">
            <div class="text item">
              <el-form-item label="角色">
                <el-checkbox-group v-model="roleListDataByid">
                  <el-checkbox v-for="city in roleListDataList" :label="city.key" :key="city.key" @change="roleChanges">{{city.label}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </div>
          </el-card>
        </el-col>
      </el-row>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="myVisible = false">取消</el-button>
      <el-button type="primary" v-bind:loading="buttonLoading" @click="dataFormSubmit">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { validPhone } from '@/utils/validate'
import head_Png from "@/assets/img/avatar.png";
import { insertUser, updateUser, getUserDetail } from '@/api/auth/user'
import { getAllRole } from '@/api/auth/role'

export default {
  props: ['dialogFormVisible'],
  data() {
    const idValidatePhone = (rule, value, callback) => {
      if (!validPhone(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    return {
      head_Png,
      myVisible: this.dialogFormVisible,
      buttonLoading: false,
      disabledInput: false,
      imageUrl: '',
      roleListDataList: [],
      roleListDataByid: [],
      checkListData: [],
      statusMap: {
        create: '新增',
        update: '编辑'
      },
      dataForm: {
        id: 0,
        userName: '',
        password: '',
        realName: '',
        avatar: '',
        phone: '',
        sex: '1',
        status: 1,
        roleIdList: []
      },
      rules: {
        userName: [
          { required: true, message: '用户名不能为空' },
          { max: 30, message: '最多输入 30 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空' },
          { max: 50, message: '最多输入 50 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, trigger: 'blur', validator: idValidatePhone },
          { max: 20, message: '最多输入 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    dialogFormVisible(val) {
      // 监听父元件中传来的dialogFormVisible属性是否变化，变化则赋值给副本myVisible
      this.myVisible = val
    },
    myVisible(val) {
      // 修改父元件的值
      this.$emit('update:dialogFormVisible', val)
    }
  },
  methods: {
    selectList(id) {
      this.dataForm.id = id
      this.roleListDataList = []
      getAllRole().then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.roleListDataList.push({
            key: response.data[i].id,
            label: response.data[i].name
          })
        }
      }).then(() => {
        this.myVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
        })
      }).then(() => {
        if (!this.dataForm.id) {
          this.disabledInput = false
          this.buttonLoading = false
          this.roleListDataByid = []
          this.imageUrl = this.head_Png
          this.resetDataForm()
        } else {
          this.disabledInput = true
          // 修改
          getUserDetail(this.dataForm.id).then((response) => {
              var data = response.data
              this.dataForm.userName = data.userName
              this.dataForm.realName = data.realName
              this.dataForm.avatar = data.avatar
              this.dataForm.phone = data.phone
              this.dataForm.sex = data.sex
              this.dataForm.status = data.status
              this.roleListDataByid = data.roleIdList
              this.checkListData = this.roleListDataByid
              if(data.avatar!=null && data.avatar!=""){
                  this.imageUrl = "data:image/jpg;base64," + data.avatar;
                }else{
                  this.imageUrl = this.head_Png
                }
              this.dataForm.password = ''
          })
        }
      })
    },
    roleChanges(row) {
      this.checkListData = this.roleListDataByid
    },
    resetDataForm() {
      this.dataForm = {
        id: 0,
        userName: '',
        password: '',
        realName: '',
        avatar: '',
        phone: '',
        sex: '1',
        status: 1,
        roleIdList: []
      }
    },
    dataFormSubmit() {
      this.buttonLoading = true
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (!this.dataForm.id) {
            this.dataForm.roleIdList = this.checkListData
            insertUser(this.dataForm).then((response) => {
              this.$notify({
                message: '新增成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.myVisible = false
                  this.buttonLoading = false
                  this.$emit('refreshDataList')
                }
              })
            }).catch(()=>{
              this.buttonLoading = false
            })
          } else {
            this.dataForm.roleIdList = this.checkListData
            updateUser(this.dataForm).then((response) => {
              this.$notify({
                message: '修改成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.myVisible = false
                  this.buttonLoading = false
                  this.$emit('refreshDataList')
                  if(this.$store.getters.userName == this.dataForm.userName){
                    this.$store.commit('SET_AVATAR', this.dataForm.avatar)
                    this.$store.commit('SET_NAME', this.dataForm.realName)
                  }
                }
              })
            }).catch(()=>{
              this.buttonLoading = false
            })
          }
        } else {
          this.buttonLoading = false
        }
      })
    },
    handleCancel() {
      // 点击叉叉
      var self = this
      self.myVisible = false
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 1

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片 只能是JPG 格式 或者 png格式!')
        return
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 1MB!')
        return
      }
      this.uploadFile(file)
      return isJPG && isLt2M
    },
    uploadFile(file) {
      const formData = new FormData()
      formData.append('file', file)
      uploadPicture(formData).then(response => {
        if (response.data.state === 'true') {
          this.imageUrl = 'data:image/jpg;base64,' + response.data.msg
          this.dataForm.avatar = response.data.msg
          this.$notify({
            title: '成功',
            message: '上传成功',
            type: 'success',
            duration: 2000
          })
        } else {
          this.$notify({
            title: '失败',
            message: response.data.msg,
            type: 'error',
            duration: 2000
          })
        }
      })
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

